package by.jtraining.london.repo.Impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.jtraining.london.model.Lector;
import by.jtraining.london.repo.LectorRepository;

import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

/**
 * @author Pakhomova Irina
 * 
 */

public class LectorRepositoryImpl extends GenericRepositoryImpl<Lector, Long>
		implements LectorRepository {
	private static final Logger LOG = LoggerFactory
			.getLogger(LectorRepositoryImpl.class);

	@Inject
	public LectorRepositoryImpl(EntityManager entityManager) {
		super(entityManager, Lector.class);
	}

	@Transactional
	public void add(Lector lector) {
		LOG.debug("Trying to persist {}", lector);
		em.persist(lector);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Lector> getLectorsSortedByActive() {//not works
		LOG.debug("Trying to find all persisted objects of {} sorted by activity and course",
				Lector.class.getSimpleName());
		Query query = em
				.createQuery("SELECT l FROM Lector l ORDER BY l.isActive DESC , l.course DESC");
		List<Lector> entities = query.getResultList();
		LOG.debug("{} lector(s) found.", entities.size());
		return entities;
	}

	@Transactional
	public boolean getIsActiveForLector(long id){
		LOG.debug("Trying to get lector");
		Lector lector = getById(id);
		return lector.getIsActive();
	}
	
	@Transactional
	public void reverseIsActiveForLector(long id){
		LOG.debug("Trying to reverse a state is_active for lector");
		Lector lector = getById(id);
		LOG.debug("Old state is_active={}",lector.getIsActive());
		lector.setIsActive(lector.getIsActive()?false:true);
		LOG.debug("New state is_active={}",lector.getIsActive());
		save(lector);
        LOG.debug("Save changes");
	}
	
}
